package cn.mark.test.serlvet;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns="/async/*", asyncSupported=true)
public class AsyncServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		resp.getWriter().println("Upload start");
		super.service(req, resp);
//		
//		System.out.println("getContextPath" + req.getContextPath());
//		System.out.println("getServletPath" + req.getServletPath());
//		System.out.println("getPathInfo" + req.getPathInfo());
//		
//		HttpSession session = req.getSession();
//		
//		System.out.println("Session ID: " + session.getId());
//		
//		
//		resp.getWriter().println("req.getRequestURI(): " + req.getRequestURI());
//		resp.getWriter().println("resp.encodeURL(req.getRequestURI()): " + resp.encodeURL(req.getRequestURI()));
////		resp.encodeURL(req.getRequestURI()); // 会将sessionId保持在URL,如果client设置cookie允许，则保持不变
//		
//		
//	
//		
//		
//		resp.getWriter().println("World2");
//		
////		req.getRequestDispatcher("/report2").include(req, resp);
////		req.getRequestDispatcher("/report2").forward(req, resp);
//		
//		resp.getWriter().println("getRequestDispatcher end");
		
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		System.out.println("isReady 1: " + req.getInputStream().isReady());
		AsyncContext acontext = req.startAsync();
		
		System.out.println("isReady: 2" + req.getInputStream().isReady());
		
		acontext.start(new Thread(()-> {
			try {
				Thread.currentThread().sleep(1000 * 10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("acontext.getResponse() == resp" + (acontext.getResponse() == resp));
			
			try {
				acontext.getResponse().getWriter().write("async is complete");
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			
			acontext.complete();
		}));
		
		System.out.println("isReady: 3" + req.getInputStream().isReady());
		
		resp.getWriter().write("fisrt hellos");
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub

	}
	
	
	
}
